package juc.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock extends AQS implements Lock {
    @Override
    public void lock() {
        acquire(1);
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {
        return acquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {
        release(1);
    }

    @Override
    public Condition newCondition() {
        return null;
    }

    @Override
    boolean tryAcquire(int arg) {
        int c = getState();
        if (c == 0) {
            // 尝试获取锁
            if (stateCas(0,1)) {
                // 设置独自线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
        }
        // 锁重入
        if (Thread.currentThread().equals(getExclusiveOwnerThread())) {
            setState(c + arg);
            return true;
        }
        return false;
    }

    @Override
    public boolean tryRelease(int arg) {
        if (!Thread.currentThread().equals(getExclusiveOwnerThread())) {
            throw new RuntimeException("不是当前线程加的锁!,OwnerThread="+getExclusiveOwnerThread());
        }
        int c = getState() - arg;
        setState(c);
        if (c == 0) {
            setExclusiveOwnerThread(null);
            return true;
        }
        return false;
    }
}
